package com.wsfk.ssm.intercepts;

import java.util.ArrayList;
import java.util.regex.Pattern;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.wsfk.ssm.entity.User;

/**
 * 检查登陆状态的拦截器
 * @author zhangbao
 *
 */

public class CheckLoginIntercept extends AbstractInterceptor{

	/**
	 * 
	 */
	private static final long serialVersionUID = 5370472645761166627L;
	private String excludingPattern;
	private Pattern[] eps;

	@Override
	public String intercept(ActionInvocation arg0) throws Exception {
		
		HttpSession session = ServletActionContext.getRequest().getSession(true);
		User user = (User)session.getAttribute("user");
		//如果是不需要登录的访问 不需要检查
		if (user != null || noCheckUrl(ServletActionContext.getRequest().getRequestURI())) {
			return arg0.invoke();
		}
		return "tologin";
	}
	
	private boolean noCheckUrl(String url) {
		if (eps == null || eps.length == 0) {
			return false;
		}

		for (Pattern p : eps) {
			if (p.matcher(url).find()) {
				return true;
			}
		}

		return false;
	}
	
	public String getExcludingPattern() {
		return excludingPattern;
	}

	public void setExcludingPattern(String excludingPattern) {
		this.excludingPattern = excludingPattern;

		if (this.excludingPattern != null) {
			String[] es = this.excludingPattern.split("[,;]");
			ArrayList<Pattern> ls = new ArrayList<Pattern>();
			for (String e : es) {
				ls.add(Pattern.compile(e.trim()));
			}

			eps = new Pattern[ls.size()];
			ls.toArray(eps);
		}
	}

}
